<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\BaseController;
use App\Models\UserCollectArticle;
use App\Models\UserCollectBrand;
use App\Models\UserCollectCourse;
use Illuminate\Http\Request;

class CollectController extends BaseController
{

    // 收藏的文章
    public function article(Request $request)
    {
        $params = $this->validate($request,[
            'type' => 'required|in:1,2,3,4,5',
            'keyword' => 'string|max:100'
        ]);

        $type = $params['type'];
        $user_id = auth('api')->id();
        $query = UserCollectArticle::query()
            ->selectRaw('*,(select sum(view_count) from article_browses where
                        article_id=user_collect_articles.article_id) as view_count')
            ->with('article')
            ->where('user_id',$user_id)
            ->where('status',1);

        if (isset($params['keyword'])){
            $keyword = $params['keyword'];
            $query->whereHas('article',function ($q) use ($keyword,$type){
                $q->where('title','like','%'.$keyword.'%')->where('type',$type);
            });
        }else{
            $query->whereHas('article',function ($q) use($type){
                $q->where('type',$type);
            });
        }



        $articles = $query->orderByDesc('id')
                        ->simplePaginate();

       return $this->success($articles);
    }

    // 收藏的品牌
    public function brand(Request $request)
    {
        $params = $this->validate($request,[
            'keyword' => 'string|max:100'
        ]);

        $user_id = auth('api')->id();
        $query =  UserCollectBrand::query()
            ->where('user_id',$user_id)
            ->with(['brand' => ['profile']])
            ->where('status',1);




        if (isset($params['keyword'])){
            $keyword = $params['keyword'];
            $query->whereHas('brand',function ($q) use ($keyword){
                $q->where('name','like','%'.$keyword.'%');
            });
        }

        $articles = $query->orderByDesc('id')->simplePaginate();

        return $this->success($articles);
    }

    // 收藏的课程
    public function course(Request $request)
    {
        $user_id = auth('api')->id();


        $params = $this->validate($request,[
            'keyword' => 'string|max:100'
        ]);

        $query =  UserCollectCourse::query()
                            ->where('user_id',$user_id)
                            ->with(['course' => ['auth:user_id,name']])
                            ->where('status',1);

        if (isset($params['keyword'])){
            $keyword = $params['keyword'];
            $query->whereHas('course',function ($q) use ($keyword){
                $q->where('name','like','%'.$keyword.'%');
            });
        }


        $articles = $query->orderByDesc('id')->simplePaginate();

        return $this->success($articles);
    }


}
